import React, { useEffect } from 'react';
import { useLocation } from '@docusaurus/router';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';

import { setLoginMessage } from '@site/src/constants/index';

const Callback: React.FC = () => {
  const location = useLocation();
  const {
    siteConfig: {customFields},
  } = useDocusaurusContext();

  const params = new URLSearchParams(location.search);
  const code = params.get('code') || '';
  const from = params.get('from') || '/';

  useEffect(() => {

    if (!from.startsWith('/')) {
      window.location.href = '/';
      return;
    }

    const fetchToken = async () => {
      try {
        const response = await fetch(`${customFields.apiUrl}/api/auth/v1/getToken?code=${code}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
        });

        if (response.ok) {
          const result = await response.json();

          // 存储访问令牌
          setLoginMessage(result.user.access_token);
          window.location.href = from;
        } else {
          window.location.href = '/';
        }
      } catch (error) {
        console.error('网络错误或其他异常:', error);
        window.location.href = '/';
      }
    };
    fetchToken();
  }, [code, from]);

  return (
    <main>
      正在登录，请稍候...
    </main>
  );
};

export default Callback;